import tagApi from "@rc/apis/rc/tag.mjs";

import ModuleTitle from "./module-title.vue";
import CascaderProject from "@rc/pages/components/async/cascader-project.vue";
import CascaderCourse from "@rc/pages/components/async/cascader-course.vue";
import SelectSubject from "@rc/pages/components/async/select-subject.vue";
import SelectYear from "@rc/pages/components/async/select-year.vue";
import SelectPeriod from "@rc/pages/components/async/select-period.vue";
import ChapterDialog from "@rc/pages/components/chapter-tree-dialog/index.vue";
import KnowledgeDialog from "@rc/pages/components/knowledge-tree-dialog/index.vue";

export default {
	props: {
		// 回显初始化需要的数据，传入时的格式与字段起码与projectBaseObj变量保持一致才能正常回显
		defaultData: {
			type: Array,
			default: () => []
		},
		// 是否展示章节知识点关联部分
		isShowRelevance: {
			type: Boolean,
			default: false
		},
		// 是否不允许编辑主要信息,如果为true，则已保存的项目和科目不允许删除和修改（科目可以添加）
		notEditMain: {
			type: Boolean,
			default: false
		}
	},
	components: {
		ModuleTitle,
		CascaderProject,
		CascaderCourse,
		SelectSubject,
		SelectYear,
		SelectPeriod,
		ChapterDialog,
		KnowledgeDialog
	},
	data() {
		return {
			selectIndex: 0, // 当前编辑的表单下标
			isShowChapterDialog: false, // 是否显示章节编辑弹窗
			isShowKnowledgeDialog: false, // 是否显示知识点编辑弹窗
			formList: [], // 项目表单集合
			rules: {
				// 表单规则
				projectId: [{ required: true, message: "请选择项目", trigger: "change" }],
				subjectList: [{ required: true, message: "请选择科目", trigger: "change" }],
				seriesCourseList: [{ required: true, message: "请选择系列课", trigger: "change" }],
				applicableYearId: [{ required: true, message: "请选择适用年份", trigger: "change" }],
				examCycleId: [{ required: true, message: "请选择考试周期", trigger: "change" }]
			},
			// 添加新项目的模板对象，使用时使用深复制，避免污染此模板
			projectBaseObj: {
				projectId: [], // 项目id
				projectName: "", // 项目名称
				subjectList: [], // 科目id集合
				subjectFullList: [], // 完整的科目列表集合，包含名称
				seriesCourseList: [], // 系列课id集合
				applicableYear: "", // 适用年份
				applicableYearId: "", // 适用年份id
				examCycleId: "", // 考试周期标识
				examCycleName: "", // 考试周期名称
				// 以下的资源编辑才用得上(this.isShowRelevance == true)
				rcChapterList: [], // 章节目录集合
				rcCknowledgeList: [] // 知识点集合
			},
			subjectListCache: [], // 当前项目下选中科目的列表集合
			chapterRulesObj: {
				// 章节规则配置信息
				isRequired: false, // 是否必填
				projectIds: [] // 开启的项目id集合
			},
			knowledgeRulesObj: {
				// 知识点规则配置信息
				isRequired: false, // 是否必填
				projectIds: [] // 开启的项目id集合
			}
		};
	},
	computed: {
		// 判断一个项目id是否在章节配置列表中
		isInChapterRules() {
			return (projectId) => {
				return this.chapterRulesObj.projectIds.some((i) => i === "0000" || i === projectId);
			};
		},
		// 判断一个项目id是否在知识点的配置列表中
		isInKnowledgeRules() {
			return (projectId) => {
				return this.knowledgeRulesObj.projectIds.some((i) => i === "0000" || i === projectId);
			};
		}
	},
	methods: {
		// 查询章节知识点类型列表
		queryChapterKnowledgeList() {
			tagApi.queryChapterKnowledgeList({
				success: (data) => {
					this.chapterKnowledgeList = data;
					data.forEach((item) => {
						switch (item.theirType) {
							case "C":
								this.chapterRulesObj.isRequired = item.isRequired === "Y";
								this.chapterRulesObj.projectIds = item.projectVos.map((i) => i.projectId);
								break;
							case "K":
								this.knowledgeRulesObj.isRequired = item.isRequired === "Y";
								this.knowledgeRulesObj.projectIds = item.projectVos.map((i) => i.projectId);
								break;
						}
					});
				}
			});
		},
		// 更新当前选中的科目信息
		updateSubjectListCache() {
			const index = this.selectIndex;
			const checkSubjectList = this.formList[index].subjectList;
			this.subjectListCache = this.$refs.subjectSelect[index].api_getOptions();
			this.subjectListCache = this.subjectListCache.map((i) => ({ subjectId: i.subjectId, subjectName: i.subjectName }));
			this.subjectListCache = this.subjectListCache.filter((i1) => checkSubjectList.some((i2) => i1.subjectId === i2));
		},
		// 更新覆盖章节列表
		updateChapter(arr = []) {
			this.formList[this.selectIndex].rcChapterList = arr;
			this.formList[this.selectIndex].isSaveStatus = false;
		},
		// 更新覆盖知识点列表
		updateKnowledge(arr = []) {
			this.formList[this.selectIndex].rcCknowledgeList = arr;
			this.formList[this.selectIndex].isSaveStatus = false;
			this.isShowKnowledgeDialog = false;
		},
		/**
		 * 当项目不存在于项目列表时，禁用该项目
		 * @param {Array} projectList 扁平化的项目列表
		 * @param {object} item 当前的项目详情
		 */
		projectReadyDisable(projectList, item) {
			if (item.projectId.length && !projectList.some((i) => i.projectId === item.projectId[item.projectId.length - 1])) {
				this.$set(item, "isDisableProject", true);
			}
		},
		// 点击添加项目
		clickAddProject() {
			if (this.formList.length > 9) {
				this.$message.warning("最多只能添加10个项目");
				return;
			}
			this.formList.push({
				...this.projectBaseObj,
				originalProjectId: "", // 原项目id
				isSaveFull: false, // 默认保存的信息是否完整
				isSaveStatus: false // 当前状态是否保存
			});
			this.selectIndex = this.formList.length - 1;
		},
		// 点击删除项目
		clickDelProject(item, index) {
			// 最后一条已保存项目不允许删除
			if (item.isSaveStatus && this.formList.filter((i) => i.isSaveStatus).length === 1) {
				this.$message.warning("已保存项目至少保留1个");
				return;
			}
			// 缓存删除的执行函数
			const delFun = () => {
				this.formList.splice(index, 1);
				if (index < this.selectIndex) {
					// 删除当前选中项目之前的项目，当前下标减一
					this.selectIndex -= 1;
				} else if (index === this.selectIndex) {
					// 删除当前选中项目，定位到第一个
					this.selectIndex = 0;
				}
			};

			if (item.isSaveStatus) {
				// 如果是已保存状态,需要从接口中删除
				this.$emit("delete", item.originalProjectId, (isSuccess) => {
					if (isSuccess) {
						// 父级提交成功，从缓存中删除
						delFun();
					}
				});
			} else {
				// 如果是未保存状态,直接从缓存中删除
				delFun();
			}
		},
		// 修改项目
		changeProject({ oldData, newData }, item, index) {
			if (this.formList.some((i) => i.projectId[i.projectId.length - 1] === newData[newData.length - 1])) {
				this.$message.warning("该项目已存在，请勿重复添加");
				item.projectId = [];
				// 疑似ui组件缺陷，无法对入参快速变化进行响应，加个延时器
				setTimeout(() => {
					item.projectId = oldData;
					item.projectName = oldData.length ? this.$refs.projectCascader[index].api_getCheckedNodes()[0].label : "";
				}, 20);
				return;
			}
			item.projectId = newData;
			item.isSaveStatus = false; // 项目变动，改为未保存状态
			// 清除科目信息
			item.subjectList = [];
			// 清除系列课信息
			item.seriesCourseList = [];
			// 清除年份
			item.applicableYearId = "";
			// 清除考试周期
			item.examCycleId = "";
			if (this.isShowRelevance) {
				// 清除章节目录
				item.rcChapterList = [];
				// 清除知识点
				item.rcCknowledgeList = [];
			}
			// 疑似ui组件缺陷，无法对入参快速变化进行响应，加个延时器
            setTimeout(() => {
                item.projectName = this.$refs.projectCascader[index].api_getCheckedNodes()[0].label;
            },20);
		},
		// 修改科目
		changeSubject(item) {
			if (this.isShowRelevance) {
				// 去除掉不属于当前科目下的章节和知识点
				item.rcChapterList = item.rcChapterList.filter((i1) => item.subjectList.some((i2) => i2 === i1.subjectId));
				item.rcCknowledgeList = item.rcCknowledgeList.filter((i1) => item.subjectList.some((i2) => i2 === i1.subjectId));
			}
			item.isSaveStatus = false;
		},
		/**
		 * 年份数据加载完成
		 * @param {array} options
		 * @param {object} item 当前实例对象
		 */
		yearLoadReady(options, item) {
			// 如果当前没有选择年份，默认选择当前年份
			if (!item.applicableYearId) {
				const yearStr = String(new Date().getFullYear());
				const findItem = options.find((i) => i.projectyearYear === yearStr);
				if (findItem) {
					item.applicableYearId = findItem.projectyearId;
					item.applicableYear = findItem.projectyearYear;
				}
			}
		},
		/**
		 * 周期数据加载完成
		 * @param {array} options
		 * @param {object} item 当前实例对象
		 */
		periodLoadReady(options, item) {
			// 如果不是保存状态，说明是切换了项目或年份，默认选择第一个周期
			if (!item.isSaveStatus && options.length) {
				item.examCycleId = options[0].pypId;
				item.examCycleName = options[0].pypseqName;
			}
		},
		// 删除章节列表项
		delChapterItem(item, index) {
			item.rcChapterList.splice(index, 1);
			item.isSaveStatus = false;
		},
		// 删除知识点列表项
		delKnowledgeItem(item, index) {
			item.rcCknowledgeList.splice(index, 1);
			item.isSaveStatus = false;
		},
		// 点击保存项目
		onSubmit(index) {
			this.$refs.form[index].validate((isValid) => {
				if (!isValid) {
					return false;
				}
				// 表单基础验证通过
				const params = JSON.parse(JSON.stringify(this.formList[index]));
				params.projectId = params.projectId[params.projectId.length - 1];
				// 章节或知识点在开启列表中并且是必填项时进行校验
				if (this.isInChapterRules(params.projectId) && this.chapterRulesObj.isRequired && !params.rcChapterList.length) {
					this.$message.warning("请至少关联一个章节");
					return;
				}
				if (this.isInKnowledgeRules(params.projectId) && this.knowledgeRulesObj.isRequired && !params.rcCknowledgeList.length) {
					this.$message.warning("请至少关联一个知识点");
					return;
				}
				// 全部校验完成，准备提交
				if (this.isShowRelevance) {
					params.rcChapterList = params.rcChapterList.map((i) => ({
						subjectName: i.subjectName,
						subjectId: i.subjectId,
						chapterId: i.chapterId,
						chapterName: i.chapterName
					}));
					params.rcCknowledgeList = params.rcCknowledgeList.map((i) => ({
						subjectName: i.subjectName,
						subjectId: i.subjectId,
						knowledgeId: i.knowledgeId,
						knowledgeName: i.knowledgeName
					}));
				}
				const itemsDetail = {
					project: params.isDisableProject
						? [{ value: params.projectId, label: params.projectName }]
						: this.$refs.projectCascader[index].api_getCheckedNodes(), // 选中的项目信息[],
					subject: this.$refs.subjectSelect[index].api_getOptions().filter((i1) => params.subjectList.some((i2) => i1.subjectId === i2)), // 选中的科目信息[]
					course: this.$refs.courseCascader[index].api_getCheckedNodes(), // 选中的系列课信息[],
					year: this.$refs.yearSelect[index].api_getOptions().find((i) => i.projectyearId === params.applicableYearId), // 选中的年份信息{}
					period: this.$refs.periodSelect[index].api_getOptions().find((i) => i.pypId === params.examCycleId) // 选中的考试周期信息{}
				};
				this.$emit("submit", params, itemsDetail, (isSuccess) => {
					if (isSuccess) {
						// 父级提交成功，将数据改为已保存状态
						this.formList[index].isSaveStatus = true;
						this.formList[index].isSaveFull = true;
						this.formList[index].originalProjectId = params.projectId;
						if (this.notEditMain) {
							// 不允许编辑主要字段的类型，配上相应的数据
							this.formList[index].notEditMain = true;
							this.formList[index].oldSubjectList = JSON.parse(JSON.stringify(params.subjectList));
						}
					}
				});
			});
		}
	},
	created() {
		if (this.isShowRelevance) {
			this.queryChapterKnowledgeList();
		}
		if (this.defaultData.length) {
			this.formList = this.defaultData.map((i) => ({
				...i,
				originalProjectId: i.projectId[0],
				oldSubjectList: JSON.parse(JSON.stringify(i.subjectList)), // 保存一份之前的科目信息，用于需要时禁用
				isSaveStatus: true, // 当前状态是否保存
				isSaveFull: i.isFullyEdited === "N" ? false : true, // 当前保存的信息是否完整，当isSaveStatus为true时才有意义
				notEditMain: this.notEditMain // 传来的数据都是已保存过的,根据配置确定是否允许编辑
			}));
		} else {
			this.clickAddProject();
		}
	}
};
